<?php
/**
 * Лента пользователей
 *
 * @package default
 * @author Alexander Sibiryakov
 **/
class AggregatedModel_Feed_ReaderUsers implements AggregatedModel_Feed_FeedInterface
{
	private $page_citems = 10;
	private $items;
	private $community_oid;
	private $filter_by_jq;
	private $page_number;
	private $no_pager;
	private $order_direction;

	public $rh;

	/**
	 * Устанавливает параметры модели.
	 * Возможные параметры: community_oid, filter_by_jq (только то что в очереди), page_number, no_pager
	 *
	 * @return void
	 * @author Alexander Sibiryakov
	 **/
	public function setModelParams($key, $value) {
		$this->$key = $value;
	}

	/**
	 * Извлекает данные
	 *
	 * @return void
	 * @author Alexander Sibiryakov
	 **/
	public function doStuff() {
		$this->generateQuery();
		$this->getCounts();

		$this->rh->useClass("AggregatedModel_ItemProcessor_Interface");
		$this->rh->useClass("AggregatedModel_ItemProcessor_Common");
		$this->rh->useClass("AggregatedModel_ItemProcessor_MemberField");
		$mf = new AggregatedModel_ItemProcessor_MemberField($this->rh);

		$mf->setParam("community_oid", $this->community_oid);

		$rs = $this->rh->ctx->store->findSQL( $this->main_sql );

		if (!$rs) { /* echo "there is no available feed for you"; */ return false; }
		$i = array();
		while ($obj = $rs->next()) {
			$row = $rs->rs->current();
			$data = array_merge($obj->data, $row);

			$data = $mf->processItem($data);

			$i[] = $data;
		}
		$this->items = $i;

		if ($this->page_number > 1)
			$this->page['prev'] = $this->page_number - 1;

		if ($this->items_count - ($this->page_number * $this->page_citems) > 0)
			$this->page['next'] = $this->page_number + 1;
	}

	private function generateQuery() {
		$prefix = $this->rh->ctx->db->db_prefix;
		$offset = ($this->page_number-1) * $this->page_citems;
		if ( $offset < 0 ) {
			$offset = 0;
		}

		$additional_joins = "";

		if (isset($this->filter_by_jq)) {
			// если нас просят отфильтровать по очереди на вступление в сообщество то искать в множестве
			// полученном через роли бесполезно потому пользователей _еще_ нет в сообществе
			$fields_to_select = "objs.*";
			$body = " FROM {$prefix}class_joinqueue jq
			INNER JOIN {$prefix}objects objs ON objs.oid=jq.user_oid
			";

			$where = " WHERE jq.community_oid = ".$this->community_oid;
			/*
			$additional_joins .= " INNER JOIN {$prefix}class_user ou ON ou.oid = u.id_object
			INNER JOIN {$prefix}class_joinqueue jq ON jq.user_oid = ou.oid AND jq.community_oid = ".$this->community_oid;
			*/
		} else {
			$fields_to_select = "objs.*, role_ids.id_object AS role_oid, r.title AS role_title";
			$body = " FROM (
			SELECT l2.id, l2.id_object FROM t_subject_relations parent
			LEFT OUTER JOIN t_subject_relations l1 USE INDEX (`pid+id`) ON l1.parent_id = parent.id AND l1.id_object=0
			LEFT OUTER JOIN t_subject_relations l2 USE INDEX (`pid+id`) ON l2.parent_id = l1.id
			WHERE parent.id_object = ".$this->community_oid."
			) as role_ids
			INNER JOIN t_subject_relations u USE INDEX (`pid+id`) ON u.parent_id=role_ids.id
			INNER JOIN {$prefix}objects objs ON objs.oid=u.id_object
			INNER JOIN {$prefix}class_role r ON r.oid=role_ids.id_object
			";
			$where = "";
		}


		if (isset($this->no_pager)) {
			$limit = "";
		} else $limit = " LIMIT ".$offset.", ".$this->page_citems;

		$order_by = "";

		if ($this->order_direction == "desc") {
			$order_type = " DESC ";
		} else {
			$order_type = " ASC ";
		}

		if (isset($this->order_by)) {
			switch ($this->order_by) {
				case "name":
				$order_by = " ORDER BY ou.fullname ".$order_type;
				$additional_joins = " INNER JOIN {$prefix}class_user ou ON ou.oid = objs.oid ";
				break;

				case "status":
				$order_by = " ORDER BY r.oid ".$order_type;
				break;

				case "date":
				$order_by = " ORDER BY member.join_date ".$order_type;

				if (!isset($this->filter_by_jq))
					$additional_joins = " INNER JOIN {$prefix}class_member member ON member.user_oid = objs.oid AND member.community_oid = ".$this->community_oid;

				break;
			}

		}

		if (isset($this->filter_by_jq)) {
			$this->main_sql = "SELECT ".$fields_to_select.$body.$additional_joins.$where.$limit;
		} else {
			$this->main_sql = "SELECT ".$fields_to_select.$body.$additional_joins.$where.$order_by.$limit;
		}

		$this->count_sql = "SELECT COUNT(*) as count ".$body.$additional_joins.$where;
	}

	private function getCounts() {
		if (!isset($this->count_sql)) {
			debug("there is no sql for query count");
			die();
		}
		$rs_count = $this->rh->ctx->store->findSQL( $this->count_sql );
 		if ($rs_count) {
 			$res = $rs_count->next()->data['count'];
			$this->items_count = $res;

 		} else {
			$res = FALSE;
 		}

		return $res;

	}

	/**
	 * Возвращает массив с записями, обычно он напрямую уходит в шаблоны, поэтому его поля следует искать там
	 *
	 * @return array
	 * @author Alexander Sibiryakov
	 **/
	public function getItems() {
		return $this->items;
	}

	/**
	 * Возвращает массив с данными для подгрузки и постраничного пролистывания вида
	 *	return array(
	 *		"prev"=>$this->page['prev'],
	 *		"next"=>$this->page['next'],
	 *		"overall_items_count"=>$this->items_count,
	 *		"items_generated"=>count($this->items),
	 *		"items_per_page"=>$this->$this->page_citems
	 *		);
	 *
	 * @return array
	 * @author Alexander Sibiryakov
	 **/
	public function getPager() {
		return array(
			"prev"=>$this->page['prev'],
			"next"=>$this->page['next'],
			"overall_items_count"=>$this->items_count,
			"items_generated"=>count($this->items),
			"items_per_page"=>$this->page_citems
			);
	}

	/**
	 * Очищает внутренние переменные, так что экземпляр готов к повторному использованию
	 *
	 * @return void
	 * @author Alexander Sibiryakov
	 **/
	public function clean() {

	}


} // END class
